/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 * sschaffe
 *
 * File Info:
 * User: sschaffe
 * Date: 2011/01/20
 * Time: 17:22
 *
 * Project: KiWi2, kiwi-core module
 */

package kiwi.core.webservices.search;

import kiwi.core.api.config.ConfigurationService;
import kiwi.core.api.query.SparqlService;
import kiwi.core.api.triplestore.TripleStore;
import org.slf4j.Logger;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;

/**
 * This webservice processes requests to the SOLR query service and resolves all queries to RDF properties by querying
 * the triple store. It performs the following rewritings:
 * <ul>
 * <li>for each query of the form <code>PREFIX:PROPERTY:QUERY</code> (e.g. <code>rdfs:comment:KiWi</code>), the
 *     namespace of the query is looked up in the triple store and PREFIX:PROPERTY in the query is replaced by
 *    the URI of the property and the filter continues with step 2 </li>
 * <li>for each query of the form <code>URI:QUERY</code> (e.g. <code>http://www.w3.org/2000/01/rdf-schema#comment:KiWi</code>),
 *    the URI is mapped to the internal field names of the KiWi index depending on type; the type can be specified as part
 *    of the QUERY in the form QSTRING^^TYPE and can be one of "text", "literal", "int" or "double"; if no type is given,
 *    the type defaults to text.
 * </li>
 * </ul>
 * Generische Suche (solr und sparql)

url:
	baseURL/KiWi2/search/select
queryParameter:
	q = queryString (MANDATORY)
	lang = Sprache (eig. nur für SOLR relevant)
	qt = 'kiwi' oder 'sparql' (queryType)
	wt = zB 'json' oder 'xml' (returnType !ACHTUNG! bei  solr ist zur Zeit nur der JSON Response Writer üerschrieben und liefert die korrekten Ergebnisse)
Ergebis:
	redirect auf service

generic SOLR:
url:
	baseURL/KiWi2/search/solr/select
queryParameter:
	q = s.o.
	lang = s.o.
	wt =  s.o.
Ergebnis:
	redirect auf service

sprachspezifisch SOLR:
url:
	baseURL/KiWi2/solr/{core}/select
queryParameter:
	q = s.o.
	lang = s.o.
	wt =  s.o.
Ergebnis:
	result

SPARQL:
url:
	baseURL/KiWi2/query/sparql
queryParameter:
	q = s.o.
	wt =  s.o.
Ergebnis:
	result
 * <p/>
 * See also: http://www.kiwi-community.eu/display/KIWI/KiWi+2+SearchWebService
 * User: sschaffe
 */
@ApplicationScoped
@Path("/search")
public class SearchWebService {

	public static final String DEFAULT_QT = "solr";
	public static final String DEFAULT_WT = "json";

    @Inject
    private Logger log;

    @Inject
    private ConfigurationService configurationService;

    @Inject
    private TripleStore tripleStore;

	@Inject
	private SparqlService sparqlService;

    private Set<String> languages;

    @PostConstruct
    public void initialize() {
        languages = new HashSet<String>(configurationService.getListConfiguration("solr.cores"));

        log.info("Starting SOLR Querying WebService for languages {}",languages);
    }

	@GET
    @Path("/select")
	public Response search(@Context HttpServletRequest request,
						   @QueryParam("qt")@DefaultValue(DEFAULT_QT) String queryType,
						   @QueryParam("lang") String language,
						   @QueryParam("q") String q,
						   @QueryParam("wt")@DefaultValue(DEFAULT_WT) String returnType) throws URISyntaxException, UnsupportedEncodingException {
		//SOLR
		if(queryType.equals("kiwi")) {
			return search(request,language);
		}

		//SPARQL
		//TODO queryType.equals("serql") || queryType.equals("serqo")
		if(queryType.equals("sparql")) {
			try {
				return Response.seeOther(new URI(null,null,"/query/sparql","q="+q+"&wt="+returnType,null)).build();
			} catch(Exception e) {
				return Response.serverError().entity("some error in query url").build();
			}

		}
		return Response.status(400).entity("QueryType "+queryType+" is not supported").build();
	}

	@GET
    @Path("/solr/select")
	public Response search(@Context HttpServletRequest request,
						   @QueryParam("lang") String language) throws URISyntaxException, UnsupportedEncodingException {
			String core;
			if(language == null) {
				core = configurationService.getStringConfiguration("solr.core.generic");
			} else {
				//remove from queryString
				if(!languages.contains(language)) {
					log.warn("language {} not supported; reverting to generic SOLR index",language);
					language = "generic";
				}
				core = configurationService.getStringConfiguration("solr.core."+language);
			}
			return Response.seeOther(new URI(configurationService.getBaseUri() + "solr/" + core + "/select?" + request.getQueryString())).build();
	}
}
